package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.MallProtocol;
import com.rockcent.mall.lib.domain.enumclass.ProtocolType;
import com.rockcent.mall.lib.dto.MallProtocolDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.MallProtocolRepository;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by zhangjh on 2016/12/20.
 */
@RestController
public class MallProtocolController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallProtocolController.class);


    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private MallProtocolRepository mallProtocolRepository;

    /**
     *
     * @api {get} /mall/protocols/list M端协议管理列表
     * @apiGroup MALL_PROTOCOLS
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {Long} id 协议ID
     * @apiSuccess {String} title 协议标题
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} content 协议内容
     * @apiSuccess {Long} versionNo 协议版本号
     * @apiSuccess {String=CUSTOMER_PROTOCOL("C端用户注册绑定手机"), MERCHANT_PROTOCOL("商户服务协议")} protocolType 协议类型
     * @apiSuccessExample {json} Success-Response:
     * {"
     * code":"1",
     * "desc":"成功",
     * "data":[
     * {
     *    "id":1,
     *    "title":"管理列表",
     *    "lastUpdated":"2016-11-15 14:38:35",
     *    "content":"为空表示查询顶级分类列表，不为空表示该parentId下的子分类列表",
     *    "versionNo": 1,
     *    "protocolType":"CUSTOMER_PROTOCOL"
     * },
     * .......
     * ]
     * }
     */
    @RequestMapping(value = Routes.MALL_PROTOCOLS_LIST, method = RequestMethod.GET)
    public JsonResult listProtocols(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            List<MallProtocol> mallProtocolList = mallProtocolRepository.findByMallIdAndExpireAndIsDeleteOrderByLastUpdatedDesc(userInfoDto.mall.getId(), Whether.NO, Whether.NO);
            jsonResult.data = mallProtocolList;
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /mall/protocols/info M端协议管理详情
     * @apiGroup MALL_PROTOCOLS
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String=CUSTOMER_PROTOCOL("C端用户注册绑定手机"), MERCHANT_PROTOCOL("商户服务协议")} protocolType 协议类型
     *
     * @apiSuccess {Long} id 协议ID
     * @apiSuccess {String} title 协议标题
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} content 协议内容
     * @apiSuccess {Long} versionNo 协议版本号
     * @apiSuccess {String=CUSTOMER_PROTOCOL("C端用户注册绑定手机"), MERCHANT_PROTOCOL("商户服务协议")} protocolType 协议类型
     *
     * @apiSuccessExample {json} Success-Response:
     * {"
     * code":"1",
     * "desc":"成功",
     * "data":[
     *  {
     *    "id":1,
     *    "title":"管理列表",
     *    "lastUpdated":"2016-11-15 14:38:35",
     *    "content":"为空表示查询顶级分类列表，不为空表示该parentId下的子分类列表",
     *    "versionNo": 1,
     *    "protocolType":"CUSTOMER_PROTOCOL"
     *  }
     * ]
     * }
     */
    @RequestMapping(value = Routes.MALL_PROTOCOLS_INFO, method = RequestMethod.GET)
    public JsonResult protocolsInfo(HttpServletRequest request, MallProtocolDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getProtocolType()) || !EnumUtils.isValidEnum(ProtocolType.class, dto.getProtocolType())) {
                jsonResult.remind("CUSTOMER_PROTOCOL(\"C端用户注册绑定手机\"), MERCHANT_PROTOCOL(\"商户服务协议\")",log);
                return;
            }
            MallProtocol mallProtocol = mallProtocolRepository.findByMallIdAndExpireAndProtocolTypeAndIsDelete(userInfoDto.mall.getId(), Whether.NO, ProtocolType.valueOf(dto.getProtocolType()), Whether.NO);
            jsonResult.data = mallProtocol;
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {post} /mall/protocols/update M端协议更新
     * @apiGroup MALL_PROTOCOLS
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必传参数</code> 协议ID
     * @apiParam {String} title <code>必传参数</code> 协议标题
     * @apiParam {String} content <code>必传参数</code> 协议内容
     * @apiParam {String=CUSTOMER_PROTOCOL("C端用户注册绑定手机"), MERCHANT_PROTOCOL("商户服务协议")} protocolType <code>必传参数</code> 协议类型
     *
     * @apiSuccessExample {json} Success-Response:
     * {"
     * code":"1",
     * "desc":"成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_PROTOCOLS_UPDATE, method = RequestMethod.POST)
    public JsonResult saveProtocol(@RequestBody MallProtocolDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MallProtocol.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            if (dto.getTitle() == null) {
                jsonResult.remind("title 不能为空",log);
                return;
            }
            if (dto.getContent() == null) {
                jsonResult.remind("content 不能为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getProtocolType()) || !EnumUtils.isValidEnum(ProtocolType.class, dto.getProtocolType())) {
                jsonResult.remind("CUSTOMER_PROTOCOL(\"C端用户注册绑定手机\"), MERCHANT_PROTOCOL(\"商户服务协议\")",log);
                return;
            }
            MallProtocol mallProtocol = mallProtocolRepository.findByMallIdAndExpireAndProtocolTypeAndIsDelete(userInfoDto.mall.getId(), Whether.NO, ProtocolType.valueOf(dto.getProtocolType()), Whether.NO);
            if (mallProtocol == null) {
                jsonResult.remind(MallProtocol.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            //将旧数据置于过期
            mallProtocol.setExpire(Whether.YES);
            mallProtocolRepository.save(mallProtocol);

            //新增一条数据
            MallProtocol protocol = new MallProtocol();
            protocol = new MallProtocol();
            protocol.setMallId(userInfoDto.mall.getId());
            protocol.setTitle(dto.getTitle());
            protocol.setContent(dto.getContent());
            protocol.setVersionNo(mallProtocol.getVersionNo() + 1L);
            protocol.setProtocolType(mallProtocol.getProtocolType());
            protocol = mallProtocolRepository.save(protocol);
        };

        return doing.go(request, log);
    }

}
